package Java面试周阳.引用;

import java.lang.ref.SoftReference;

public class SoftReferenceDemo {
    public static void main(String[] args) {
//        softRefMemoryEnough();
        softRefMemoryNotEnough();
    }

    private static void softRefMemoryEnough() {
        // 创建一个强引用
        Object o1 = new Object();
        // 创建一个软引用
        SoftReference<Object> softReferenceDemo = new SoftReference(o1);
        System.out.println(o1);
        System.out.println(softReferenceDemo.get());

        o1 = null;
        // 手动GC
        System.gc();

        System.out.println(o1);
        System.out.println(softReferenceDemo.get());
    }

    public static void softRefMemoryNotEnough() {
        System.out.println("==========================");
        // 创建一个强应用
        Object o1 = new Object();
        // 创建一个软引用
        SoftReference<Object> softReference = new SoftReference(o1);
        System.out.println(o1);
        System.out.println(softReference.get());

        o1 = null;

        // 模拟oom自动GC
        try {
            // 创建30M大对象
            byte[] bytes = new byte[30*1024*1024];
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            System.out.println(o1);
            System.out.println(softReference.get());
        }
    }
}
